package cn.tjad.tjad2.module.form.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.FormDetail;
import cn.tjad.tjad2.data.bean.Id;
import cn.tjad.tjad2.data.event.SimpleEvent;
import cn.tjad.tjad2.module.form.adapter.FormDetailAdapter;
import cn.tjad.tjad2.module.form.entity.UpdateFormRequestBean;
import cn.tjad.tjad2.module.form.views.AttachmentSelectWidget;
import cn.tjad.tjad2.module.form.views.UserSelectWidget;
import cn.tjad.tjad2.module.form.views.ViewPortView;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;

@Route(path = PageId.FORM_HANDLE)
public class FormHandleFrament extends BaseFragment implements AdapterView.OnItemSelectedListener {

    @BindView(R.id.form_handle_spinner)
    Spinner spinner;
    @BindView(R.id.form_handle_recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.form_handle_submit)
    Button submit;

    private ArrayList<FormDetail.FormDetailStep> formStepDetails;
    private FormDetailAdapter formDetailAdapter;
    private int formId;

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.form_handle_fragment, null);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            formStepDetails = (ArrayList<FormDetail.FormDetailStep>) bundle.getSerializable(Keys.FORM_DETAIL_STEPS);
            formId = bundle.getInt(Keys.FORM_ID, -1);
        }
        if (formStepDetails == null || formId == -1) {
            Tools.showToast("参数错误，页面显示异常");
            return;
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        formDetailAdapter = new FormDetailAdapter();
        formDetailAdapter.setEditable(true);
        formDetailAdapter.setShowGroup(false);
        recyclerView.setAdapter(formDetailAdapter);
        String[] spinnerSelects = new String[formStepDetails.size()];
        for (int i = 0; i < spinnerSelects.length; i++) {
            spinnerSelects[i] = formStepDetails.get(i).step.name;
        }
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, spinnerSelects);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(this);
        spinner.setSelection(0);
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.setCenterText("表单处理");
    }

    @OnClick(R.id.form_handle_submit)
    public void onSubmit(View view) {
        if (!checkContents()) {
            return;
        }
        int checkedIndex = spinner.getSelectedItemPosition();
        FormDetail.FormDetailStep editStep = formStepDetails.get(checkedIndex);
        ProgressDialogUtils.show(getContext());
        UpdateFormRequestBean requestBean = new UpdateFormRequestBean();
        if (editStep.id > 0) {
            requestBean.id = editStep.id;
        }
        requestBean.consStatus = 1;
        if (editStep.step != null) {
            requestBean.step = new Id(editStep.step.id);
        }
        List<FormDetail.FormStepDetail> formStepDetails = editStep.details;
        requestBean.details = new ArrayList<>();
        if (formStepDetails != null && formStepDetails.size() > 0) {
            for (FormDetail.FormStepDetail detail: formStepDetails) {
                UpdateFormRequestBean.Detail d = new UpdateFormRequestBean.Detail();
                d.detail = new Id(detail.detail.id);
                d.value = detail.value;
                requestBean.details.add(d);
            }
        }
        RetrofitManager.getInstance().getApiService()
                .updateForm(Tools.getProjectId(), formId, requestBean)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<BaseBean>(compositeDisposable) {
                    @Override
                    public void onSuccess(CommonBean<BaseBean> t) {
                        ProgressDialogUtils.dismiss();
                        new AlertDialog.Builder(getContext())
                                .setTitle("提示")
                                .setMessage("操作成功！")
                                .setCancelable(false)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        EventBus.getDefault().post(new SimpleEvent(7001));
                                        getActivity().finish();
                                    }
                                })
                                .show();
                    }

                    @Override
                    public void onFailed(String message) {
                        Tools.showToast(message);
                        ProgressDialogUtils.dismiss();
                    }
                });

    }

    private boolean checkContents() {
        return true;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        formDetailAdapter.setFormStep(formStepDetails.subList(position, position + 1));
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View view = recyclerView.getChildAt(i);
            if (view != null) {
                UserSelectWidget targetView = view.findViewById(R.id.user_select_widget);
                if (targetView != null) {
                    targetView.onActivityResult(requestCode, resultCode, data);
                }
                ViewPortView viewPortView = view.findViewById(R.id.view_port);
                if (viewPortView != null) {
                    viewPortView.onActivityResult(requestCode, resultCode, data);
                }
                AttachmentSelectWidget attachWidget = view.findViewById(R.id.attach_select_widget);
                if (attachWidget != null) {
                    attachWidget.onActivityResult(requestCode, resultCode, data);
                }
            }
        }
    }
}
